package org.longs.converter;

import lombok.Getter;
import org.longs.bean.WdfHeader;
import org.longs.config.Constant;
import org.longs.stream.LittleAccessFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WdfWavConverter extends BaseConverter {

    private WdfHeader wdfHeader;

    @Getter
    private List<WavConverter> wavConverters;

    private Map<String, WavConverter> wasConverterMap;

    public Map<String, WavConverter> getWasConverterMap() {
        return wasConverterMap;
    }

    public void setWasConverterMap(Map<String, WavConverter> wasConverterMap) {
        this.wasConverterMap = wasConverterMap;
    }

    public WdfHeader getWdfHeader() {
        return wdfHeader;
    }

    public void setWdfHeader(WdfHeader wdfHeader) {
        this.wdfHeader = wdfHeader;
    }

    public WdfWavConverter(String filePath) {
        super(filePath);
    }

    public WdfWavConverter(LittleAccessFile randomAccessFile) {
        super(randomAccessFile);
    }

    @Override
    public String getFlag() {
        return Constant.WDF_FLAG;
    }

    @Override
    public void analysisBody(LittleAccessFile randomAccessFile) throws IOException {
        wdfHeader = new WdfHeader();
        wdfHeader.setFileCount(randomAccessFile.readLittleInt());
        wdfHeader.setOffsetStart(randomAccessFile.readLittleInt());
        wasConverterMap = new HashMap<>();
        wavConverters = new ArrayList<>();
        randomAccessFile.seek(0);
        randomAccessFile.skipBytes(wdfHeader.getOffsetStart());
        for (int i = 0; i < wdfHeader.getFileCount(); i++) {
            WavConverter recorder = new WavConverter(randomAccessFile);
            recorder.setName(Integer.toHexString(randomAccessFile.readLittleInt()));
            recorder.setOffset(randomAccessFile.readLittleInt());
            recorder.setTotal(randomAccessFile.readLittleLong());
            wavConverters.add(recorder);
            wasConverterMap.put(recorder.getName(), recorder);
        }
    }
}
